import os
import pandas as pd
from flask import Flask
from flask_cors import *
import collections

app = Flask(__name__)
CORS(app, supports_credentials=True)  # 解决ajax的跨域访问问题


@app.route("/")
def index():
    # return render_template("index.html")
    return '开启后台服务器'


@app.route("/data", methods=['GET', 'POST'])
def get_data1():
    data = pd.read_csv('D:\桌面\考研大数据\数据分析\数据统计.csv', encoding='GBK')
    province = data['省/市'][:10].values.tolist()    # 省/市
    nums = data['学院总数'][:10].values.tolist()   # 学院个数   # 学院个数
    college_sum = int(data['学院总数'].sum())
    students = int(data['招生总人数'].sum())
    return {"province": province, 'colleges': nums, "college_sum": college_sum, 'students': students}


@app.route("/mathEnglish", methods=['GET', 'POST'])
def get_data2():
    data = pd.read_csv(r'D:\桌面\考研大数据\数据分析\数据统计.csv', encoding='GBK')
    English1 = list(data['英语（一）'])
    English2 = list(data['英语（二）'])
    Math1 = list(data['数学（一）'])
    Math2 = list(data['数学（二）'])
    college_sum = int(data['学院总数'].sum())
    # print(sum(English1), sum(English2), sum(Math1), sum(Math2))
    labels = ['英语（一）', '英语（二）', '数学（一）', '数学（二）']
    nums = [sum(English1), sum(English2), sum(Math1), sum(Math2)]
    aver = []
    for i in range(0, 4):
        aver.append(int(nums[i]/college_sum*100))
    return {'labels': labels, 'nums': nums, 'aver': aver}


@app.route("/wordCloud", methods=['GET', 'POST'])
def word_cloud():
    folder_path = 'D:\桌面\考研大数据\数据分析\dataWash'  # 需要读取的文件夹
    csv_files = [os.path.join(folder_path, f) for f in os.listdir(
        folder_path) if f.endswith('.csv')]  # 提取文件夹里的所有csv文件
    word_list = []  # 存词
    for file in csv_files:
        data = pd.read_csv(file, header=0)  # 开始读取csv文件
        for obj in data['考试科目']:  # 存考试专业科目
            word_list.append(obj.split(')')[-1])
        for college in data['院系所']:  # 存院系
            word_list.append(college.split(')')[-1])
        for zhuanye in data['专业']:  # 存专业
            word_list.append(zhuanye.split(')')[-1])
        for research in data['研究方向']:  # 存研究方向
            word_list.append(research.split(')')[-1])
    word_counts = collections.Counter(word_list)
    words_list = word_counts.most_common(30)
    # print(str(words_list[0]))
    lists = []
    key = ['name', 'value']
    key_words = []
    for words in words_list:
        word = str(words)
        name = word.split(',')[0].split('\'')[1]
        num = int(word.split(',')[1].split(')')[0])
        lists = [name, num]
        key_words.append(dict(zip(key, lists)))
    return {'key_words': key_words}


@app.route("/proStu", methods=['GET', 'POST'])
def pro_stu():
    df = pd.read_csv('D:\桌面\考研大数据\数据分析\数据统计.csv', encoding='GBK')
    data = df.sort_values('招生总人数', ascending=False)
    students = list(data['招生总人数'])[:8]    # 招生总人数取前15
    province = list(data['省/市'])[:8]  # 省/市15
    key = ['value', 'name']
    key_value = []
    for i in range(0, len(students)):
        lists = [students[i], str(province[i])]
        key_value.append(dict(zip(key, lists)))
    # key_value = dict(zip(key, lists))
    return {'key_value': key_value}


@app.route("/map", methods=['GET', 'POST'])
def map_data():
    data = pd.read_csv('D:\桌面\考研大数据\地图可视化\data\大学（维度_经度）.csv', encoding='GBK')
    # print(data['大学名'])  # name
    # data['经度']        #log
    # data['维度']        #lat
    log_lat = []
    name = []
    data1 = {'name': '学校'}
    list1 = []
    list_all = []
    # data_university = '{'+ 'name'+':'+ "学校" +'}'
    for i in range(0, len(data['大学名'])):
        log_lat.append([data['经度'][i], data['维度'][i]])
        name.append(data['大学名'][i])
        # key_value.append((dict(zip(name, log_lat))))
        list1.append(data1)
        list1.append(dict(name=data['大学名'][i]))
        # print(list1)
        list_all.append(list1)
        list1 = []
    key_value = dict(zip(name, log_lat))
    return {'key_value': key_value, 'list_all': list_all}


if __name__ == "__main__":
    print("-------------------------正在开启后端服务-------------------------")
    app.run(debug=True)
